/**
 * @Description:
 * @author 紫霞
 * @since 2019/1/17
 */
// React基础组件
import React from 'react'
// dva 连接组件 - 连接route和model
import { connect } from 'dva'
// 引入antd的组件
import { Row, Input,Col, Card,Cascader,Select, Button, Tabs, Form, Popconfirm, Modal,Table, Badge, Menu, Dropdown, Icon } from 'antd'
//导入路由组件，用于跳转等
import { Link, hashHistory } from 'dva/router'
// 导入项目全局配置文件
import config from 'config/config'

// 引入model取值工具方法
import { mapStateToProps } from 'utils/view_utils'
//引用listPage
import ListPage from 'widget/PageTmpl/ListPage_pageSize'
import Keypress from 'widget/Keypress'

// 当前组件样式
import styles from './commissionListStyle.less'
import { Grid, QueryCondition } from 'widget/Grid/index'
import { AdvanceSearch } from 'widget/CollapsiblePanels/index'
import { chunk } from 'lodash'

import classnames from 'classnames/bind'

//权限管理
import FlagBtn from 'widget/FlagBtn/FlagView'
import moment from 'moment/moment'
import Cookie from 'js-cookie'

let cx = classnames.bind(styles)

/**
 * description 路由视图及事件处理
 * dispatch 分发到models中的effects对应事件名
 * model 用于获取models中state定义的数据
 * form 表单对象
 */
const TabPane = Tabs.TabPane
const FormItem = Form.Item;
const { TextArea } = Input;
const formItemLayout = {
    labelCol: { span: 5 },
    wrapperCol: { span: 15 },
}
//  信用代码 orgCode  中介公司名称 orgName  合作状态 state 法人 legalMan  合作有效时间  门店合作码 cooperationCode  报备人数 recommendNum  成交数  dealNum
const routeView = function ({dispatch, model, form}) {
  // 表单的子函数
  const {resetFields, getFieldDecorator, validateFields, setFieldsValue} = form
  // 取出model对象，命名空间
  const {modelObj, namespace} = model
  let {showTabelModal,modalTitle,cityList,loading, btnLoading, modalObj, currentItem,  statisticsInfo,biz,defaultExpandedRowKey,areaList,estateList,commissionInfo} = modelObj
    // modelObj.xxx获取model中状态机的值
  console.log('modelObj', modelObj)
  // 点击处理事件
  const clickHandler = (e) => {
    // 分发到model文件中effects的xxx方法
    dispatch({
      type: `${namespace}/xxx`,
      payload: {}
    })
  }
  
  
  
  //修改状态
  const changeState = (payload) => {
    dispatch({
      type: `${namespace}/updateStore`,
      payload: {...payload}
    })
  }
  
  // 详情页跳转
  function routerGo ({url = '', query = {}}) {
    hashHistory.push({
      pathname: url,
      query: query
    })
  }
    function onChange(value) {
        commissionInfo.province = value[0]
        commissionInfo.city = value[1]
        dispatch({
            type: `${namespace}/updateStore`,
            payload: { commissionInfo }
        });
        new Promise((resolve) => {
            dispatch({
                type: `${namespace}/getEstateList`,
                payload: { province: value[0], city: value[1],resolve}
            })
        }).then((res) => {
            console.log(res)
            form.setFieldsValue({roductId:res[0]?res[0].productId:null})
        })

    }
    //原因查询
    function showModal(actionType, item) {
        //resetFields()
        if (actionType == 'reasonSearch') {
            dispatch({
                type: `${namespace}/reasonSearch`,
                payload: {
                    showTabelModal: true,
                    modalTitle: '原因查询',
                    actionType: "reasonSearch",
                    detailData: {
                        city: '',
                        projectName: "",
                        mobile:"",
                        reason: ""
                    },
                }
            });
        }
    }
    //原因查询确定
    function handleOk() {
        validateFields((err, values) => {
            console.log("原因查询确定")
            console.log(values)
            if (err) {
                return false
            }
            dispatch({
                type: `${namespace}/getReason`,
                payload: {
                    productId:values.productId,
                    mobile:values.mobile
                }
            });
        })
    }
    function inputChange(e, type,idx) {
        console.log("项目改变")
        console.log(e)
        if (type == 'productId' ) {
            commissionInfo.productId=e
        }
        dispatch({
            type: `${namespace}/updateStore`,
            payload: { commissionInfo }
        });

        console.log(e, type)

    }
    //新建/编辑取消
    function handleCancel() {
        dispatch({
            type: `${namespace}/reasonSearch`,
            payload: { showTabelModal: false }
        });
    }

    // 获取项目选项
    function getPorjectOption() {
        return estateList.map((item, idx) => {
            return <Select.Option key={idx} value={item.productId}>{item.name}</Select.Option>
        })
    }
   
  let pageProps = {
    // biz:{
    //   queryForm:{
    //     startTime:moment().startOf('month'),
    //     endTime:moment().endOf('month'),
    //   }
    // },
    ui: {
      'api_url': '3rd/commission/recommendCommission',
      //'api_url': '3rd/commission/test',
      'method': 'POST',
      'headers': {
        "Content-type": "application/json" ,
      },
      'app': '',
      'params': `accountId=${Cookie.get(config.cookie.userId)}`,
      'timeout':'600000',
      // "mockData": mockData,
      'mockData': null,
      refreshByEnter: true,  //监控键盘事件，自动刷新数据
      'search_bar': {     //区域 项目 认购时间段
        'fields': [
          {
            en_name: 'regionId',
            zh_name: '区域',
            elem_type: 'Select',
            elem_valid_type: 'string',
            cmpt_items: modelObj.areaList||[]
          },
          {
            en_name: 'projectName',
            zh_name: '项目',
            elem_type: 'Input',
            elem_valid_type: 'string',
          },
          {
            en_name: 'date',
            zh_name: '认购时间段',
            elem_type: "Date",
            format: "YYYY-MM-DD",
            // double: true,
            split_keys: ['startTime', 'endTime'],
            elem_valid_type: "string" ,
          },
        ],
        searchHandler: () => {
          console.log('search click')
        },
        resetHandler: () => {
          biz.queryForm.startTime=moment().startOf('month').format('YYYY-MM-DD')
          biz.queryForm.endTime=moment().endOf('month').format('YYYY-MM-DD')
          changeState({biz})
          console.log('reset click')
        },
        searchCallback: params => {
          console.log('search finish', params)
        },
        pasteTargetList: [
          'carName',
        ],
        actions:
        [
          {'label':"原因查询",
              render:()=>{
                  return <Button type="primary" onClick={() =>{
                      dispatch({
                          type: `${namespace}/reasonSearch`,
                          payload: {
                              showTabelModal:true,
                              modalTitle:"原因查询"
                          }
                      })
                  }}>原因查询</Button>
              }}
        ]
      },
      action_bar: [
        {
          label: '导出',
          type: 'primary',
          render:()=>{
            return <Button type="primary" loading={modelObj.exportLoading} onClick={() =>{
              dispatch({
                type: `${namespace}/exportList`,
                payload: {}
              })
            }}>导出</Button>
          }
        },
      ],
      // 序号 经纪人姓名 联系方式 身份证号 身份类型 员工部门 钱包ID 入账银行 银行卡号 推介时间 推介客户姓名 联系方式 推介区域  推介楼盘  置业顾问  认购时间  认购归属时间  房号  业态  认购金额  签约时间  签约归属时间  签约金额  是否需结佣  不需结佣原因  是否首付齐 佣金表编制日期 佣金（税前） 佣金(税后) 佣金发放时间
      'table':
        {
          'status_params': 'status=0',
          'status_text': '全部',
          'scroll': {x: 2400},
          'fields': [
            // {
            //   "en_name": "key",
            //   "zh_name": "序号",
            //   width: 60,
            //   render: (a, item, index, d, e, f) => {
            //     return index + 1
            //   },
            // },
            {
              'en_name': 'agentName',
              'zh_name': '经纪人姓名',
              width:80,
            },
            {
              'en_name': 'agentMobile',
              'zh_name': '联系方式',
              width: 130,
            },
            {
              'en_name': 'agentIdCardNo',
              'zh_name': '身份证号',
              width: 190,
            },
            {
              'en_name': 'agentIdentity',
              'zh_name': '身份类型',
              width: 120,
            },
            {
              'en_name': 'agentDepartment',
              'zh_name': '员工部门',
              width: 120,
            },
            {
              'en_name': 'lLWalletId',
              'zh_name': '钱包ID',
              width: 210,
            },
            {
              'en_name': 'bankName',
              'zh_name': '入账银行',
              width: 120,
            },
            {
              'en_name': 'bankCard',
              'zh_name': '银行卡号',
              width: 190,
            },
            {
              'en_name': 'recommendedTime',
              'zh_name': '推介时间',
              width:180,
            },
            {
              'en_name': 'customerName',
              'zh_name': '推介客户姓名',
              width:80,
            },
            {
              'en_name': 'customerMobile',
              'zh_name': '联系方式',
              width: 130,
            },
            {
              'en_name': 'recommendedArea',
              'zh_name': '推介区域',
              width: 150,
            },
            {
              'en_name': 'productName',
              'zh_name': '推介楼盘',
            },
            {
              'en_name': 'consultantName',
              'zh_name': '置业顾问',
              width: 80,
            },
            {
              'en_name': 'subscribeTime',
              'zh_name': '认购时间',
              width: 80,
            },
            {
              'en_name': 'subscribeAscriptionTime',
              'zh_name': '认购归属时间',
              width: 130,
            },
            {
              'en_name': 'roomNo',
              'zh_name': '房号',
              width: 80,
            },
            {
              'en_name': 'formats',
              'zh_name': '业态',
              width: 80,
            },
            {
              'en_name': 'subscribeMoney',
              'zh_name': '认购金额',
              width: 80,
            },
            {
              'en_name': 'signTime',
              'zh_name': '签约时间',
              width: 130,
            },
            {
              'en_name': 'signAscriptionTime',
              'zh_name': '签约归属时间',
              width: 130,
            },
            {
              'en_name': 'signMoney',
              'zh_name': '签约金额',
              width: 80,
            },

            {
              'en_name': 'whetherCommission',
              'zh_name': '是否需结佣',
              width: 60,
            },
            {
              'en_name': 'unwantedCommission',
              'zh_name': '不需结佣原因',
              width: 80,
            },
            {
              'en_name': 'payment',
              'zh_name': '是否首付齐',
              width: 60,
            },
            {
              'en_name': 'commissionFormTime',
              'zh_name': '佣金表编制日期',
              width: 80,
            },
            {
              'en_name': 'pretaxCommission',
              'zh_name': '佣金（税前）',
              width: 80,
            },
            {
              'en_name': 'aftertaxCommission',
              'zh_name': '佣金(税后)',
              width: 80,
            },
            {
              'en_name': 'commissionGrantTime',
              'zh_name': '佣金发放时间',
              width: 130,
            },
          ],
          action_props: {
            // width: 195,
          },
          actions: [
          ],
        },
      
    },
  }
  
  if (!!modelObj.biz) {
    pageProps.biz = modelObj.biz
    pageProps.biz.syncBackCbf = (biz) => {
      // console.log(biz)
      dispatch({
        type: `${namespace}/updateStore`,
        payload: {biz}
      })
    }
  }
  
  return (
    <div className={cx('pageLayout')}>
      <div className="public_listMain list">
        <ListPage pageProps={pageProps}/>
        <Modal
            title={modalTitle}
            visible={showTabelModal}
            onOk={()=>{console.log('131212');handleOk()}}
            onCancel={handleCancel}
        >
          <Row>
            <Col className="col" span={20}>
              <FormItem {...formItemLayout}
                        label="城市">
                  {getFieldDecorator(`city`, {
                      initialValue:[`${commissionInfo.province}`,`${commissionInfo.city}` ],
                      rules: [
                          {
                              required: true, validator: (rule, value, callback) => {
                              console.log(commissionInfo.city)
                              if (typeof (commissionInfo.city||commissionInfo.province) == 'undefined') {
                                  callback('请选择城市')
                              } else {
                                  callback()
                              }
                          }
                          }
                      ],
                  })(
                      <Cascader options={cityList} placeholder="请选择城市"  onChange={onChange}  />
                  )}
              </FormItem>
            </Col>
          </Row>
          <Row>
            <Col className="col" span={20}>
              <FormItem {...formItemLayout}
                        label="项目">
                  {getFieldDecorator(`productId`, {
                      initialValue:[commissionInfo.productId],
                      rules: [
                          {
                              required: true, validator: (rule, value, callback) => {
                              console.log(commissionInfo.productId)
                              if (typeof (commissionInfo.productId) == 'undefined') {
                                  callback('请选择项目')
                              } else {
                                  callback()
                              }
                          }
                          }
                      ],
                  })(
                      <Select
                          notFoundContent={'该省市中无楼盘'}
                          placeholder="请选择项目"
                          allowClear
                          onChange={(e,idx) => inputChange(e, 'productId',idx)} >
                          {getPorjectOption()}
                      </Select>
                  )}
              </FormItem>
            </Col>
          </Row>
          <Row>
            <Col className="col" span={20}>
              <FormItem {...formItemLayout}
                        label="电话">
                  {getFieldDecorator('mobile', {
                      initialValue: commissionInfo.mobile,
                      rules: [
                          { required: true, whitespace: true, message: '请输入电话' },
                          {
                              validator: (rule, values, callback) => {
                                  if (values && values.length > 0) {
                                      var isPhone = /^1[3456789]\d{9}$/;//手机号码
                                      var isMob = /^(1[3456789]\d{9})|(((400)-(\d{3})-(\d{4}))|^((\d{7,8})|(\d{4}|\d{3})-(\d{7,8})|(\d{4}|\d{3})-(\d{3,7,8})-(\d{4}|\d{3}|\d{2}|\d{1})|(\d{7,8})-(\d{4}|\d{3}|\d{2}|\d{1}))$)$/ ;// 座机格式

                                      console.log(isMob.test(values))
                                      console.log(isPhone.test(values))
                                      if (isMob.test(values) || isPhone.test(values)) {
                                          callback();
                                      }
                                      else {
                                          callback("请输入正确的手机号格式");
                                      }
                                  } else {
                                      callback();
                                  }
                              }
                          }],
                  })(<Input
                      placeholder={'请输入电话'}
                      onChange={(e) => { inputChange(e.target.value, 'mobile') }}
                  />)}
              </FormItem>
            </Col>
          </Row>
          <Row>
            <Col className="col" span={20}>
              <FormItem {...formItemLayout} label="原因">
                  {getFieldDecorator('reason', {
                      initialValue: commissionInfo.reason,
                  })(<TextArea disabled={true}  rows={4}  onChange={(e) => { inputChange(e.target.value, 'reason') }} />)}
              </FormItem>
            </Col>
          </Row>
        </Modal>
      </div>
    </div>
  )
}

// 连接视图(view)和模型(model)
export default connect(mapStateToProps)(Form.create()(routeView))

